#include "widget.h"
#include "firstobject.h"
#include "secondobject.h"
#include "controller.h"

#include <QApplication>
#include <QDebug>
#include <QThread>
#include <QObject>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    qDebug() << "Main thread ID: " << QThread::currentThreadId();

    FirstObject *obj1 = new FirstObject;
    SecondObject *obj2 = new SecondObject;
    QThread *thread = new QThread;
    Controller controller(2);

    // 将对象移动到子线程
    obj1->moveToThread(thread);
    obj2->moveToThread(thread);

    // 连接任务启动信号
    QObject::connect(thread, &QThread::started, obj1, &FirstObject::TaskByFirstObject);
    QObject::connect(thread, &QThread::started, obj2, &SecondObject::TaskBySecondObject);

    // 任务完成时通知Controller
    QObject::connect(obj1, &FirstObject::signalQuit, &controller, &Controller::notifyTaskFinish);
    QObject::connect(obj2, &SecondObject::signalQuit, &controller, &Controller::notifyTaskFinish);

    // Controller通知线程退出
    QObject::connect(&controller, &Controller::allTasksFinished, thread, &QThread::quit);

    // 释放资源
    QObject::connect(thread, &QThread::finished, obj1, &FirstObject::deleteLater);
    QObject::connect(thread, &QThread::finished, obj2, &SecondObject::deleteLater);
    QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);

    QObject::connect(thread, &QThread::finished, []{
        exit(0);
    });

    // 启动线程
    thread->start();


    return a.exec();
}
